<script setup lang="ts">
import { nextTick, ref } from "vue";
import { DATE_TIME_FORMATTER } from "@chulei-ui/utils";
import dayjs from "dayjs";
import { ClGrid } from "@chulei-ui/components";
import { esi } from "../../repositories";
import { JITA_REGION_ID } from "../../constant";
import { NumberUtils } from "../../utils";
import { useCacheStore } from "../../sde/cache";

import { useMarketStore } from "../../cache/MarketStore";
import type { UniverseType } from "../../sde/entity";
import type { Grid, PageFetchParams } from "@chulei-ui/components";

import type { DogmaAttribute, MarketOrder, ProductPriceHistory } from "@scvzerng/esi-163";
import UniverseAttribute from "~components/universe-type/UniverseAttribute.vue";
import UniverseTypeMaterials from "~components/universe-type/UniverseTypeMaterials.vue";
import BlueprintManufacturing from "~components/blueprint/BlueprintManufacturing.vue";
import BlueprintInvention from "~components/blueprint/BlueprintInvention.vue";
import UniverseTypeIcon from "~components/universe-type/UniverseTypeIcon.vue";

defineOptions({
  name: "UniverseTypeDrawer",
});
type History = {
  typeId: number;
  activeTab: string;
};
const historyTypes = ref<History[]>([]);

const cacheStore = useCacheStore();
const marketStore = useMarketStore();

const type = ref<UniverseType>();
const visible = ref();
const active = ref();

const show = async (id: number) => {
  if (type.value) {
    historyTypes.value.push({ typeId: type.value.id, activeTab: active.value! });
  }
  attributes.value = (await esi.universe.type(id))!.dogma_attributes;
  type.value = cacheStore.getType(id)!;
  active.value = "attribute";
  if (type.value.materials) {
    active.value = "compose";
  }
  if (type.value.blueprint) {
    active.value = "blueprintManufacturing";
  }
  visible.value = true;
  if (historyTypes.value.length > 0) {
    historyRef.value!.refresh();
    orderRef.value!.refresh();
  }
};

const columns = ref<Grid.Column<ProductPriceHistory>[]>([
  {
    field: "date",
    headerName: "日期",
  },
  {
    field: "order_count",
    headerName: "订单数",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "volume",
    headerName: "总数量",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "highest",
    headerName: "最高价",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "lowest",
    headerName: "最低价",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "average",
    headerName: "均价",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
]);

const marketOrderColumns = ref<Grid.Column<MarketOrder>[]>([
  {
    field: "issued",
    headerName: "下单时间",
    valueGetter({ data }) {
      return dayjs(data!.issued).format(DATE_TIME_FORMATTER);
    },
  },
  {
    field: "price",
    headerName: "价格",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "is_buy_order",
    headerName: "类型",
    valueGetter({ data }) {
      return data?.is_buy_order ? "买单" : "卖单";
    },
  },
  {
    field: "volume_remain",
    headerName: "剩余数量",
  },
  {
    field: "min_volume",
    headerName: "最小交易量",
  },
  {
    field: "volume_total",
    headerName: "总数",
  },
  {
    field: "duration",
    headerName: "持续时间(天)",
  },
]);

const fetchHistory = async ({ pageNum }: PageFetchParams) => {
  if (pageNum > 1) return [];
  return esi.markets
    .history(JITA_REGION_ID, type.value!.id)
    .then((d) => {
      if (d) {
        return d.sort((l, r) => dayjs(r.date).valueOf() - dayjs(l.date).valueOf());
      }
      return [];
    })
    .catch((err) => {
      if (err.code === "Type not tradable on market!") {
        return [];
      }
    });
};

const historyRef = ref();
const orderRef = ref();
const attributes = ref<(Pick<DogmaAttribute, "attribute_id"> & { value: number })[]>();

const marketOrders = async ({ pageNum }: PageFetchParams) => {
  if (pageNum > 1) return [];
  const orders = await marketStore.getMarketOrders(type.value!.id);
  return orders
    .filter((order) => order.type_id === type.value!.id)
    .sort((a, b) => {
      // 按卖单排前面买单排后面，卖单为 false，买单为 true
      if (a.is_buy_order !== b.is_buy_order) {
        return a.is_buy_order ? 1 : -1;
      }

      // 如果是相同种类的订单，按日期排序
      return new Date(b.issued).getTime() - new Date(a.issued).getTime();
    });
};

const handleClose = (close: () => void) => {
  active.value = undefined;
  type.value = undefined;
  historyTypes.value = [];
  close();
};

const back = async () => {
  const history = historyTypes.value.pop();

  if (history) {
    type.value = cacheStore.getType(history.typeId);
    historyRef.value!.refresh();
    orderRef.value!.refresh();
    await nextTick(() => {
      active.value = history.activeTab;
    });
  }
};
const gridOptions = ref<Grid.Options>({
  //@ts-ignore
  getRowId(row) {
    return row.data.order_id;
  },
  rowClassRules: {
    "order-sell": ({ data }: { data: MarketOrder }) => data.is_buy_order,
    "order-buy": ({ data }: { data: MarketOrder }) => !data.is_buy_order,
  },
});
defineExpose({
  show,
});
</script>

<template>
  <el-drawer
    v-model="visible"
    destroy-on-close
    :before-close="handleClose"
    class="type-drawer"
    size="100%"
    :title="``"
    fullscreen
    :direction="'ttb'"
  >
    <template #header>
      <div class="flex items-center space-x-2">
        <UniverseTypeIcon v-if="type" :id="type.id" :size="35" />
        <div>
          {{ `${type?.name}(${type?.id})` }}
        </div>
        <el-button v-if="historyTypes.length > 0" type="info" size="small" @click="back">返回</el-button>
      </div>
    </template>
    <el-scrollbar v-if="type">
      <el-tabs v-model="active">
        <el-tab-pane v-if="attributes" name="attribute" label="属性">
          <UniverseAttribute :attributes="attributes" />
        </el-tab-pane>
        <el-tab-pane v-if="type.materials" name="compose" label="制造组件">
          <UniverseTypeMaterials :id="type!.id" />
        </el-tab-pane>
        <el-tab-pane v-if="type.blueprint?.manufacturing" name="blueprintManufacturing" label="蓝图制造">
          <BlueprintManufacturing :id="type.id" />
        </el-tab-pane>
        <el-tab-pane v-if="type.blueprint?.invention" name="blueprintInvention" label="蓝图发明">
          <BlueprintInvention :id="type.id" />
        </el-tab-pane>
        <el-tab-pane name="history" label="历史成交">
          <cl-grid
            ref="historyRef"
            :grid-options="{
              getRowId(row) {
                return row.data.date;
              },
            }"
            :columns="columns"
            :row-data="fetchHistory"
          />
        </el-tab-pane>
        <el-tab-pane name="order" label="市场订单">
          <cl-grid ref="orderRef" :grid-options="gridOptions" :columns="marketOrderColumns" :row-data="marketOrders" />
        </el-tab-pane>
      </el-tabs>
    </el-scrollbar>
  </el-drawer>
</template>

<style lang="scss">
.type-drawer {
  .el-scrollbar__view {
    height: 100%;
    .el-tabs {
      height: 100%;
      .el-tab-pane {
        height: calc(100% - 50px);
      }
    }
  }
}
.order {
  &-sell {
    background-color: var(--el-color-success-light-7);
  }
  &-buy {
    background-color: var(--el-color-danger-light-7);
  }
}
</style>
